import { SopChain, SopChainsResponse, SopApiParams, SopNodeLibrary, CreateSopChainRequest, CreateSopChainResponse, UpdateSopChainRequest, UpdateSopChainResponse } from '../types/sop';

// 全局缓存，避免重复请求
const sopChainsCache = new Map<string, {
  data: SopChain[];
  timestamp: number;
  promise?: Promise<SopChain[]>;
}>();

// 节点库缓存
const sopNodesCache: {
  data: Record<string, string[]> | null;
  timestamp: number;
  promise?: Promise<Record<string, string[]>>;
} = {
  data: null,
  timestamp: 0
};

// 缓存过期时间：5分钟
const CACHE_EXPIRY_TIME = 5 * 60 * 1000;

// SOP策略客群分类列表
export const SOP_CUSTOMER_PROFILES = [
  '年轻初级客户',
  '中年积累期客户', 
  '高净值中青年客户',
  '稳健养老客户',
  '激进专业客户'
];

// 生成缓存键
const generateCacheKey = (params?: SopApiParams): string => {
  const key = JSON.stringify(params || {});
  return `sop_chains_${key}`;
};

// 检查缓存是否有效
const isCacheValid = (timestamp: number): boolean => {
  return Date.now() - timestamp < CACHE_EXPIRY_TIME;
};

/**
 * SOP服务类
 */
export const sopService = {
  /**
   * 清理过期缓存
   */
  clearExpiredCache: () => {
    let clearedCount = 0;
    
    for (const [key, value] of sopChainsCache.entries()) {
      if (!isCacheValid(value.timestamp)) {
        sopChainsCache.delete(key);
        clearedCount++;
      }
    }
    
    // 清理节点库缓存
    if (!isCacheValid(sopNodesCache.timestamp) && sopNodesCache.data) {
      sopNodesCache.data = null;
      sopNodesCache.timestamp = 0;
      clearedCount++;
    }
    
    if (clearedCount > 0) {
      console.log(`清理了 ${clearedCount} 个过期的SOP缓存`);
    }
  },

  /**
   * 清理所有缓存
   */
  clearAllCache: () => {
    const count = sopChainsCache.size;
    sopChainsCache.clear();
    sopNodesCache.data = null;
    sopNodesCache.timestamp = 0;
    console.log(`清理了 ${count + 1} 个SOP缓存`);
  },

  /**
   * 获取缓存统计信息
   */
  getCacheStats: () => {
    let validCount = 0;
    let expiredCount = 0;
    
    for (const value of sopChainsCache.values()) {
      if (isCacheValid(value.timestamp)) {
        validCount++;
      } else {
        expiredCount++;
      }
    }
    
    return {
      total: sopChainsCache.size + (sopNodesCache.data ? 1 : 0),
      valid: validCount + (isCacheValid(sopNodesCache.timestamp) ? 1 : 0),
      expired: expiredCount
    };
  },

  /**
   * 获取SOP节点库列表
   * @returns 按阶段分组的节点库
   */
  getSopNodes: async (): Promise<Record<string, string[]>> => {
    try {
      // 检查缓存
      if (sopNodesCache.data && isCacheValid(sopNodesCache.timestamp)) {
        return sopNodesCache.data;
      }
      
      // 如果正在请求中，返回当前promise
      if (sopNodesCache.promise) {
        return await sopNodesCache.promise;
      }

      // 创建请求promise
      const requestPromise = (async (): Promise<Record<string, string[]>> => {
        const response = await fetch('/langchain-backend/sop/nodes', {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          }
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data: SopNodeLibrary = await response.json();
        
        if (!data.success) {
          throw new Error('API返回失败状态');
        }

        return data.nodes || {};
      })();

      // 临时缓存promise
      sopNodesCache.promise = requestPromise;

      // 等待请求完成
      const result = await requestPromise;

      // 更新缓存
      sopNodesCache.data = result;
      sopNodesCache.timestamp = Date.now();
      sopNodesCache.promise = undefined;

      return result;
    } catch (error) {
      console.error('获取SOP节点库失败:', error);
      sopNodesCache.promise = undefined;
      // 返回空对象而不是抛出错误，确保组件不会崩溃
      return {};
    }
  },

  /**
   * 获取SOP策略链列表
   * @param params 查询参数
   * @returns SOP策略链数组
   */
  getSopChains: async (params?: SopApiParams): Promise<SopChain[]> => {
    try {
      const cacheKey = generateCacheKey(params);
      const cachedData = sopChainsCache.get(cacheKey);
      
      // 检查缓存
      if (cachedData && isCacheValid(cachedData.timestamp)) {
        return cachedData.data;
      }
      
      // 如果正在请求中，返回当前promise
      if (cachedData?.promise) {
        return await cachedData.promise;
      }

      // 构建查询字符串
      const queryString = params ? '?' + new URLSearchParams(
        Object.entries(params).filter(([_, value]) => value !== undefined && value !== null)
          .map(([key, value]) => [key, String(value)])
      ).toString() : '';

      // 创建请求promise
      const requestPromise = (async (): Promise<SopChain[]> => {
        const response = await fetch(`/langchain-backend/sop/chains${queryString}`, {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          }
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data: SopChainsResponse = await response.json();
        
        if (!data.success) {
          throw new Error('API返回失败状态');
        }

        return data.chains || [];
      })();

      // 临时缓存promise
      sopChainsCache.set(cacheKey, {
        data: [],
        timestamp: Date.now(),
        promise: requestPromise
      });

      // 等待请求完成
      const result = await requestPromise;

      // 更新缓存
      sopChainsCache.set(cacheKey, {
        data: result,
        timestamp: Date.now()
      });

      return result;

    } catch (error) {
      console.error('获取SOP策略链列表失败:', error);
      // 返回空数组而不是抛出错误，确保组件不会崩溃
      return [];
    }
  },


  /**
   * 创建SOP策略链
   * @param chainData 创建策略的数据
   * @returns 创建结果
   */
  createSopChain: async (chainData: CreateSopChainRequest): Promise<{ success: boolean; chain?: SopChain; error?: string }> => {
    try {
      const response = await fetch('/langchain-backend/sop/chains', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(chainData)
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      // API直接返回创建的策略对象
      const createdChain: CreateSopChainResponse = await response.json();

      // 清理相关缓存，确保新策略能够被获取到
      sopService.clearAllCache();

      return {
        success: true,
        chain: createdChain
      };
    } catch (error) {
      console.error('创建SOP策略失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '创建策略失败'
      };
    }
  },

  /**
   * 更新SOP策略链
   * @param chainId 策略链ID
   * @param chainData 更新策略的数据
   * @returns 更新结果
   */
  updateSopChain: async (chainId: string, chainData: UpdateSopChainRequest): Promise<{ success: boolean; chain?: SopChain; error?: string }> => {
    try {
      const response = await fetch(`/langchain-backend/sop/chains/${chainId}`, {
        method: 'PUT',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(chainData)
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      // API直接返回更新后的策略对象
      const updatedChain: UpdateSopChainResponse = await response.json();

      // 清理相关缓存，确保更新后的策略能够被获取到
      sopService.clearAllCache();

      return {
        success: true,
        chain: updatedChain
      };
    } catch (error) {
      console.error('更新SOP策略失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '更新策略失败'
      };
    }
  },

  /**
   * 删除SOP策略链
   * @param chainId 策略链ID
   * @returns 删除结果
   */
  deleteSopChain: async (chainId: string): Promise<{ success: boolean; error?: string }> => {
    try {
      const response = await fetch(`/langchain-backend/sop/chains/${chainId}`, {
        method: 'DELETE',
        headers: {
          'Accept': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      // 清理相关缓存，确保删除后的策略列表是最新的
      sopService.clearAllCache();

      return {
        success: true
      };
    } catch (error) {
      console.error('删除SOP策略失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '删除策略失败'
      };
    }
  }
};

// 定期清理过期缓存（每10分钟执行一次）
if (typeof window !== 'undefined') {
  setInterval(() => {
    sopService.clearExpiredCache();
  }, 10 * 60 * 1000);
} 